<?php namespace Home\Controller;
use Hdphp\Controller\Controller;

class ContentController extends Controller{
	
	public function index(){
//		获取get.gid参数
		$gid = Q('get.gid','0','intval');
//		关联商品表和商品详情表，查询当前选中的商品的所有信息输出到页面
		$goodsData = Db::table('goodsdetail')->join('goods','goods_gid','=','gid')->where("gid={$gid}")->get();
//		$goodsAttr = Db::table('goods')->join('goodsattr','gid','=','goods_gid')
//										->join('typeattr','typeAttr_aid','=','aid')
//										->where("gid={$gid}")
//										->get();
		$goodsAttr = Db::table('goodsattr')->join('typeattr','typeAttr_aid','=','aid')->where("goods_gid={$gid} AND attr=1")->groupBy("aid")->get();
//		sp($goodsAttr);exit;
		
		
//		设置空数组
//		$temp = array();
//		遍历查询当前商品的所有规格		
		foreach ($goodsAttr as $k => $v) {
			$goodsAttr[$k]['son'] = Db::table('goodsattr')->where("goods_gid={$gid} AND typeAttr_aid={$v['aid']}")->get();
		}
		
//		sp($goodsAttrData);exit;
//		sp($attr);exit;
//		sp($goodsData);exit;



		foreach ($goodsData as $k => $v) {
//			把商品详情表里存放的路径组成数组，然后存放回去
			$img = explode('|', $v['img']);
			$goodsData[$k]['img'] = $img;
		}
		
		$attrcount = count($goodsAttr);
		
//		sp($goodsAttr);exit;
//		sp($attrcount);exit;
//		sp($goodsData);exit;

		View::with('attrcount',$attrcount);
//		分配规格到页面
		View::with('goodsAttr',$goodsAttr);
//		分配商品信息到页面
		View::with('goodsData',$goodsData);
		View::make();
	}
	
//	获取附加价格
	public function attr(){
//		获取ajax.gaid值
		$gaid = Q('post.gaid');
//		去除最右边的 ， 号
		$gaid = rtrim($gaid,',');
//		sp($gaid);exit;
//		查询当前id对应的附加价格，并且统计出来
		$added = Db::table('goodsattr')->where("gaid IN($gaid)")->field("added")->sum('added');

//		sp($temp);exit;
		echo json_encode($added);
	}
	
	public function shop(){
		$gid = Q('post.gid');
		$gaids = rtrim(Q('post.gaids'),',');
		
		$goods = new \Common\Model\Goods;
		$goodsData = $goods->where("gid={$gid}")->find();
		
		$added = Db::table('goodsattr')->where("gaid IN($gaids)")->field("added")->sum('added');
		
		$goodsattr = Db::table('goodsattr')->join('typeattr','typeAttr_aid','=','aid')->where("gaid IN($gaids)")->get();
//		sp($goodsattr);exit;
		$temp = array();
		foreach ($goodsattr as $k => $v) {
			$temp[$v['aname']] = $v['goodsvalue'];
		}
//		sp($temp);exit;
		$price = $goodsData['shopprice'] + $added;
		
		$data = array( 
		    'id'        => $gid, // 商品 ID 
		    'name'      => $goodsData['gname'],// 商品名称 
		    'num'       => Q('post.num'), // 商品数量 
		    'price'     => $price, // 商品价格 
		    'options' => $temp// 其他参数如价格、颜色、可以为数组或字符串
		);
//		sp($data);exit;
		Cart::add($data);
		echo json_encode($data);
//		sp($_SESSION);exit;
	}
	
}


 ?>